<template>
    <form id="uploadForm" action="/upload" method="post" enctype="multipart/form-data" v-show="!imageSrc">
        <input type="file" name="file" id="fileInput" @change="getLocalImage($event)">
    </form>
    <div class="image-container" v-show="imageSrc">
        <img :src="imageSrc" alt="Your Image">
        <div class="image-overlay">
            <lay-icon type="layui-icon-search" @click="showImage(imageSrc)" size="17px" color="#fff"></lay-icon>
            <lay-icon type="layui-icon-delete" @click="deleteImage" size="20px" color="#fff"></lay-icon>
        </div>
    </div>
</template>
<script setup>
/**
 * 上传文件
 */
import { ref } from 'vue';
const props = defineProps({
    imageUrl: {
        type: String,
        default: ''
    }
})
const imageSrc = ref(props.imageUrl)
const thisFile = ref()
const emit = defineEmits(['ImageFile', 'DeleteImage'])
import { layer } from "@layui/layui-vue"
const getLocalImage = (e) => {
    const file = e.target.files[0]; // 获取文件对象
    const formData = new FormData();
    formData.append('file', file);// 将
    thisFile.value = formData
    emit('ImageFile', formData)
    // 判断文件类型
    if (file) {
        const reader = new FileReader();
        // 监听读取完成事件，将结果赋给 imageUrl
        reader.onload = () => {
            imageSrc.value = reader.result;
        };
        // 读取文件内容
        reader.readAsDataURL(file);
    }

}
/**
 * 查看图片
 */
const showImage = (img) => {
    layer.photos({
        imgList: [{ src: img, alt: 'layer for vue' }]
    })
}


/**
 * 
 * 删除图片
 */
const deleteImage = () => {
    imageSrc.value = ''
    document.getElementById('fileInput').value = '';
    emit('ImageFile', '')
    emit('DeleteImage', '')
}



</script>
<style scoped>
.image-container {
    position: relative;
    display: inline-block;
}

.image-container img {
    width: 100px;
    display: block;
    max-width: 100%;
    height: auto;
}

.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
}

.image-container:hover .image-overlay {
    opacity: 1;
    cursor: pointer;
}
</style>